package it.koutifaris.travianmap.view.serversettingsview;

import it.koutifaris.travianmap.communication.urlverifier.UrlVerifierAsyncService;
import it.koutifaris.travianmap.communication.urlverifier.UrlVerifierAsyncService.VerificationHandler;
import it.koutifaris.travianmap.utils.UrlStringParser;

import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

class MapUrlVerifier {

	private static final String TAG = MapUrlVerifier.class.getName();

	private final UrlStringParser parser;
	private final MapUrlResutlHandler handler;

	public MapUrlVerifier(MapUrlResutlHandler handler) {
		this.handler = handler;
		parser = new UrlStringParser();
	}

	public void verifyServerString(String serverText) {
		String serverString = parser.getHost(serverText);
		try {
			final URL serverUrl = new URL("http://" + serverString + "/map.sql.gz");
			new UrlVerifierAsyncService().verifyResourceExists(serverUrl, new VerificationHandler() {

				@Override
				public void onResult(Boolean resourceExits) {
					if (resourceExits) {
						handler.onValidResource(serverUrl);
					} else {
						handler.onResourceNotPresent(serverUrl);
					}
				}

				@Override
				public void onError(Throwable error) {
					handler.onException(error);
				}
			});

		} catch (MalformedURLException e) {
			handler.onMalformedUrl(serverString);
		} catch (Exception e) {
			Log.e(TAG, "Unexpected exception.", e);
			handler.onException(e);
		}
	}

	interface MapUrlResutlHandler {

		void onValidResource(URL mapUrl);

		void onResourceNotPresent(URL url);

		void onMalformedUrl(String malformedUrl);

		void onException(Throwable e);
	}
}
